
import 'package:flutter/material.dart';
import 'package:flutter_trip_demo/provider/image_random_number.dart';
import 'filter_selector_style.dart';
import 'dart:math' as math;
import 'package:provider/provider.dart';

//不变的 图片过滤器选择
@immutable
class ImageFilterSelection extends StatefulWidget {
  const ImageFilterSelection({Key? key}) : super(key: key);

  @override
  _ImageFilterSelectionState createState() =>
      _ImageFilterSelectionState();
}

class _ImageFilterSelectionState extends State<ImageFilterSelection> {

  //过滤器集合
  final _filters = [
    Colors.white,
    ...List.generate(
      Colors.primaries.length,
          (index) => Colors.primaries[(index * 4) % Colors.primaries.length],
    )
  ];

  final filterColor = ValueNotifier<Color>(Colors.white);//值通知

  //过滤器改变事件
  void _onFilterChanged(value) {
    filterColor.value = value;
  }

  //构建照片 通过 滤镜
  Widget _buildPhotoWithFilter() {
    //随机数 + provider取值
    int random = math.Random().nextInt(5);//取值范围0-4
    switch(random){
      case 1:
        setImageRandomNumber(111);
        break;
      case 2:
        setImageRandomNumber(222);
        break;
      case 3:
        setImageRandomNumber(333);
        break;
      case 4:
      default:
        setImageRandomNumber(444);
        break;
    }

    return ValueListenableBuilder(
      valueListenable: filterColor,
      builder: (context, value, child) {
        final color = value as Color;//类型转换
        return Image.asset(
          //通过provider获取的值 拼接 图片地址
          'images/${context.watch<ImageRandomNumber>().randomNumber}.png',
          color: color.withOpacity(0.5),//颜色透明度
          colorBlendMode: BlendMode.color,//颜色混合模式
          fit: BoxFit.cover,//覆盖
        );
      }
    );
  }

  //构建过滤选择器
  Widget _buildFilterSelector(){
    return FilterSelectorStyle(
      onFilterChanged: _onFilterChanged,//改变事件
      filters: _filters,//过滤器集合
    );
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Stack(//堆布局--类似AndroidStudio帧布局
        children: [
          Positioned.fill(//定位 fill充满
            child: _buildPhotoWithFilter(),//使用构建照片 通过 滤镜
          ),
          Positioned(//定位到底部
            left: 0.0,
            right: 0.0,
            bottom: 0.0,
            child: _buildFilterSelector(),//构建过滤选择器
          ),
        ],
      ),
    );
  }

  //provider更改值方法封装
  void setImageRandomNumber(int num){
    Provider.of<ImageRandomNumber>(context,listen: false).setRandomNumber(num);
  }

}